const router=require('koa-router')();
const koaBody=require('koa-body');
const _=require('underscore');
const moment=require('moment');
const User=require('../models/index').User;
const Post=require('../models/index').Post;
const Archive=require('../models/index').Archive;
const tags=require('../config/config').post.tags;
const checkLogin=require('../middlewares/checkLogin');

router.get('/post',checkLogin(),async ctx=>{
    let users=await User.find({});
    await ctx.render('mock-post',{
        title:'Mock',
        loginUser:ctx.session.loginUser,
        users:users,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

router.post('/post',checkLogin(),koaBody(),async ctx=>{
    let {userId,number}=ctx.request.body;
    let postUser=await User.findOne({_id:userId});
    let now=Date.now();
    let posts=_.times(number,i=>{
        let time=new Date(	now	-	(1000*3600*24*(Math.random()*90+1)|0)	);
        return {
           title:[postUser.name,now,i].join('-'),
           tags:_.shuffle(tags).slice(0,_.random(1,5)),
           intro:new Array(2).fill(postUser.name+'的话题简介。').join(''),
           content:new Array(3).fill(postUser.name+'的话题。').join(''),
           author:postUser._id,
           time:time,
           archive:moment(time).format('YYYY-MM')
        }
    });

    let st=await save(posts);
    ctx.flash={[st.status]:st.msg};
    ctx.redirect('back');

    function save(posts) {
        return new Promise((resolve,reject)=>{
            (function IIFE(posts){
                let post=posts.pop();
                if(!post)return resolve({status:'success',msg:'全部POST模拟数据保存完成'});
                let newPost=new Post(post);
                Promise.all([
                    newPost.save(),
                    Archive.update({archive:newPost.archive},{$inc:{count:1}},{upsert:true})
                ]).then(ret=>{
                    console.log('Mock save post ret:',ret);
                    IIFE(posts);
                }).catch(err=>{
                    console.error('Mock post save err:',err);
                    reject(err);
                });

            })(posts);
        });
    }
});
module.exports=router;